//! # RustCloud 分布式追踪模块
//!
//! 提供 RustCloud 微服务框架的分布式链路追踪功能，支持 OpenTelemetry 标准
//! 和多种导出格式（Jaeger、JSON、Console等）。
//!
//! ## 核心功能
//!
//! * **分布式追踪** - 跨服务的请求链路跟踪
//! * **Span管理** - 完整的Span生命周期管理  
//! * **多种导出器** - 支持Jaeger、OpenTelemetry、Console等
//! * **高性能** - 基于Rust异步运行时，零开销抽象
//! * **标准兼容** - 兼容OpenTelemetry追踪标准
//!
//! ## 快速开始
//!
//! ```rust
//! use rustcloud_tracing::*;
//! 
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//!     let tracer = MockDistributedTracer::new();
//!     
//!     // 开始根Span
//!     let mut root_span = tracer.start_span("http_request", None).await?;
//!     tracer.add_span_tag(&mut root_span, "http.method", "GET").await?;
//!     
//!     // 开始子Span  
//!     let mut child_span = tracer.start_span("database_query", Some(&root_span)).await?;
//!     tracer.add_span_tag(&mut child_span, "db.table", "users").await?;
//!     
//!     // 完成Spans
//!     tracer.finish_span(&mut child_span).await?;
//!     tracer.finish_span(&mut root_span).await?;
//!     
//!     // 导出追踪数据
//!     let traces = tracer.export_traces(TraceExportFormat::Json).await?;
//!     println!("Exported traces: {}", traces);
//!     
//!     Ok(())
//! }
//! ```

pub mod tracer;
pub mod span;
pub mod exporters;

#[cfg(test)]
pub mod tests;

use std::collections::HashMap;
use std::time::SystemTime;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};

// 重新导出核心类型
pub use tracer::*;
pub use span::*;
pub use exporters::*;

/// 配置结果类型
pub type TracingResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;

/// 分布式追踪抽象接口
/// 
/// 提供分布式追踪的统一接口，支持多种追踪系统的插拔式实现
#[async_trait]
pub trait DistributedTracer: Send + Sync {
    /// 开始新的追踪Span
    async fn start_span(&self, operation_name: &str, parent_span: Option<&TraceSpan>) -> TracingResult<TraceSpan>;
    
    /// 结束追踪Span
    async fn finish_span(&self, span: &mut TraceSpan) -> TracingResult<()>;
    
    /// 添加标签到Span
    async fn add_span_tag(&self, span: &mut TraceSpan, key: &str, value: &str) -> TracingResult<()>;
    
    /// 添加日志到Span
    async fn add_span_log(&self, span: &mut TraceSpan, message: &str, fields: &HashMap<String, String>) -> TracingResult<()>;
    
    /// 导出追踪数据
    async fn export_traces(&self, format: TraceExportFormat) -> TracingResult<String>;
    
    /// 获取追踪统计
    async fn get_trace_statistics(&self) -> TracingResult<TraceStatistics>;
}

/// 追踪Span
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceSpan {
    /// 追踪ID
    pub trace_id: String,
    /// Span ID
    pub span_id: String,
    /// 父Span ID
    pub parent_span_id: Option<String>,
    /// 操作名称
    pub operation_name: String,
    /// 开始时间
    pub start_time: SystemTime,
    /// 结束时间
    pub finish_time: Option<SystemTime>,
    /// 标签
    pub tags: HashMap<String, String>,
    /// 日志
    pub logs: Vec<SpanLog>,
}

/// Span日志
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpanLog {
    /// 时间戳
    pub timestamp: SystemTime,
    /// 日志消息
    pub message: String,
    /// 字段
    pub fields: HashMap<String, String>,
}

/// 追踪导出格式
#[derive(Debug, Clone, PartialEq)]
pub enum TraceExportFormat {
    /// Jaeger格式
    Jaeger,
    /// OpenTelemetry格式
    OpenTelemetry,
    /// JSON格式
    Json,
}

/// 追踪统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceStatistics {
    /// 总Span数量
    pub total_spans: u64,
    /// 活跃Span数量
    pub active_spans: u64,
    /// 完成Span数量
    pub finished_spans: u64,
    /// 平均Span持续时间（毫秒）
    pub avg_span_duration_ms: f64,
    /// 采样率
    pub sampling_rate: f64,
}

/// 简单的错误类型用于追踪模块
#[derive(Debug)]
pub enum TracingError {
    InvalidOperation(String),
    InvalidData(String),
    NotFound(String),
    ExportError(String),
    NetworkError(String),
}

impl std::fmt::Display for TracingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TracingError::InvalidOperation(msg) => write!(f, "操作无效: {}", msg),
            TracingError::InvalidData(msg) => write!(f, "数据无效: {}", msg),
            TracingError::NotFound(msg) => write!(f, "未找到: {}", msg),
            TracingError::ExportError(msg) => write!(f, "导出错误: {}", msg),
            TracingError::NetworkError(msg) => write!(f, "网络错误: {}", msg),
        }
    }
}

impl std::error::Error for TracingError {}

// 便捷类型别名
pub type TraceId = String;
pub type SpanId = String;